
import json
import os
import requests

### Pipeline
# IAM user fetch Token
fetch_token_url = "https://%s/v3/auth/tokens"
# Run pipeline
run_pipeline_url = "https://%s/v5/%s/api/pipelines/%s/run"
# Fetch pipeline details
fetch_pipeline_detail_url = "https://%s/v5/%s/api/pipelines/%s/pipeline-runs/detail?pipeline_run_id=%s"
# Pipeline URL
pipeline_url = "https://%s/cicd/project/%s/pipeline/detail/%s/%s?v=1"

def api_req(method, url, headers=None, data=None):
    data = None if not data else json.dumps(data).encode("utf-8")
    resp = requests.request(method=method, url=url, headers=headers, data=data)
    if resp.status_code != 201:
        print("创建iam token失败")
        raise requests.exceptions.RequestException()
    return resp

def fetch_token(config):
    endpoint_iam = "iam.%s.myhuaweicloud.com" % config.huawei_cloud_endpoint
    return api_req(
        'POST', fetch_token_url % endpoint_iam, 
        headers={ 
            'Content-Type': 'application/json;charset=utf8'
        },
        data={
            "auth": {
                "identity": {
                    "methods": [
                        "password"
                    ],
                    "password": {
                        "user": {
                            "domain": {
                                "name": config.huawei_cloud_doname
                            },
                            "name": config.huawei_cloud_username,
                            "password": config.huawei_cloud_password
                        }
                    }
                },
                "scope": {
                    "project": {
                        "name": config.huawei_cloud_endpoint
                    }
                }
            }
        }
    ).headers['X-Subject-Token']

class Pipeline(object):
    def __init__(self, config):
        self.config = config
        self.token = fetch_token(config)

    def run_pipeline(self, payload, repo_config):
        endpoint_pipeline = "cloudpipeline-ext.%s.myhuaweicloud.com" % self.config.huawei_cloud_endpoint
        data={
            "sources": [
                {
                    "type": "code",
                    "params": {
                        "git_type": "git",
                        "git_url": payload['pull_request', 'head', 'repo', 'clone_url'],
                        "build_params": {
                            "build_type": "branch",
                            "target_branch": payload['pull_request', 'head', 'ref'],
                            "event_type": "Manual"
                        }
                    }
                }
            ]
        }
        resp = requests.request(
            method='POST', 
            url=run_pipeline_url % (endpoint_pipeline, repo_config['project_id'], repo_config['pipeline_id']), 
            headers={'X-Auth-Token': self.token},
            json=data
        )
        if resp.status_code != 200:
            print('启动流水线失败')
            raise requests.exceptions.RequestException()
        return resp

    def show_pipeline_detail(self, repo_config, pipeline_run_id):
        endpoint_pipeline = "cloudpipeline-ext.%s.myhuaweicloud.com" % self.config.huawei_cloud_endpoint
        resp = requests.request(
            method='GET',
            url=fetch_pipeline_detail_url % (endpoint_pipeline, repo_config['project_id'], repo_config['pipeline_id'], pipeline_run_id),
            headers={'X-Auth-Token': self.token},
            json={}
        )
        if resp.status_code != 200:
            print('获取流水线详情失败')
            raise requests.exceptions.RequestException()
        return resp
    
def fetch_pipeline_url(endpoint, project_id, pipeline_id, id):
    endpoint_pipeline = "devcloud.%s.huaweicloud.com" % (endpoint)
    url = pipeline_url % (endpoint_pipeline, project_id, pipeline_id, id)
    return url